package com.snail.readyvr.ui;

import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.util.AttributeSet;


/**
 * Created by wangyunpeng on 2016/3/11.
 * 自定义一个带删除按钮的输入框
 */
public class PhoneNumClearEditText extends ClearEditText {

    private String tmp = null;

    public PhoneNumClearEditText(Context context) {
        super(context);
    }

    public PhoneNumClearEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public PhoneNumClearEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void afterTextChanged(Editable s) {
        super.afterTextChanged(s);
        char c = ' ';//'-';
        String sourceStr = s.toString();
        if (tmp != null && tmp.equals(sourceStr)) {
            return;
        }
        tmp = separateString(sourceStr, 3, 4, c);

        if (!tmp.equals(sourceStr) && tmp.length() < 14) {
            setText(tmp);
            setSelection(tmp.length());
        }
    }

    /**
     * 用指定字符分隔格式化字符串
     * <br/>（如电话号为1391235678 指定startIndex为3，step为4，separator为' '经过此处理后的结果为  139 1234 5678）
     *
     * @param source     需要分隔的字符串
     * @param startIndex 开始分隔的索引号
     * @param step       步长
     * @param separator  指定的分隔符
     * @return 返回分隔格式化处理后的结果字符串
     */
    private String separateString(String source, int startIndex, int step, char separator) {
        int times = 0;
        StringBuilder tmpBuilder = new StringBuilder(source.trim());
        for (int i = 0; i < tmpBuilder.length(); i++) {
            if (i == startIndex + step * times + times) {//if(i == 3 || i == 8){
                if (separator != tmpBuilder.charAt(i)) {
                    tmpBuilder.insert(i, separator);
                }
                times++;
            } else {
                if (separator == tmpBuilder.charAt(i)) {
                    tmpBuilder.deleteCharAt(i);
                    i = -1;
                    times = 0;
                }
            }
        }
        return tmpBuilder.toString();
    }

    public String getRealPhoneNum(){
        if(!TextUtils.isEmpty(getText()))
            return getText().toString().replaceAll(" ","");
        return null;
    }
}

